﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pantry.Business;
using Pantry.Commons;

namespace Pantry.Web.Users.Controls
{
    public partial class Volunteering : System.Web.UI.UserControl
    {
        private readonly IFormatProvider _formatProvider = new CultureInfo("en-gb");
        private VolunteersBus _volunteersBus;
        private DataView _dataView;
        private static bool _isSort = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            FillServiceDataToGridview(CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroupAll.CssClass = "button-active";
        }

        #region Mothods
        /// <summary>
        /// Marks the activated.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void MarkActivated(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {
            var hId = (HiddenField)RepeaterListVoluteers.Items[e.Item.ItemIndex].FindControl("HiddenFeildContactId");
            int id = int.Parse(hId.Value);
            if (e.CommandName == "update")
            {
                _volunteersBus = new VolunteersBus();
                _volunteersBus.MarkActivated(true, id);
                FillServiceDataToGridview(CheckBoxIncludeActivate.Checked);
                Response.Redirect("VolunteeringOpportunityDetails.aspx?action=update&id=" + id);
            }
            else
            {
                Response.Redirect("VolunteeringOpportunityDetails.aspx?action=update&id=" + id);
            }
        }

        /// <summary>
        /// Fills the service to gridview.
        /// </summary>
        /// <param name="isInActived">if set to <c>true</c> [is in actived].</param>
        protected void FillServiceDataToGridview(bool isInActived)
        {
            try
            {
                _volunteersBus = new VolunteersBus();
                DataTable dataTable = _volunteersBus.SelectVolunteers(int.Parse(Request.QueryString["premisesId"]));
                _dataView = dataTable.DefaultView;
                if (!isInActived)
                {
                    _dataView.RowFilter = "IsActive = 'Yes'";
                    _dataView.Sort = "ContactName DESC";
                }

                CollectionPager.PageSize = 15;
                CollectionPager.BindToControl = RepeaterListVoluteers;
                CollectionPager.DataSource = _dataView;
                RepeaterListVoluteers.DataSource = CollectionPager.DataSourcePaged;
                RepeaterListVoluteers.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                ExceptionHandler.WriteErrorLog(ex);
            }
        }

        /// <summary>
        /// Resets the sort service.
        /// </summary>
        /// <param name="isInActived">if set to <c>true</c> [is in actived].</param>
        protected void ResetSortVoluteers(bool isInActived)
        {
            try
            {
                _volunteersBus = new VolunteersBus();
                DataTable dataTable = _volunteersBus.SelectVolunteers(int.Parse(Request.QueryString["premisesId"]));
                _dataView = dataTable.DefaultView;
                if (!isInActived)
                {
                    _dataView.RowFilter = "IsActive = 'Yes'";
                    _dataView.Sort = "ContactName ASC";
                }

                CollectionPager.PageSize = 15;
                CollectionPager.BindToControl = RepeaterListVoluteers;
                CollectionPager.DataSource = _dataView;
                RepeaterListVoluteers.DataSource = CollectionPager.DataSourcePaged;
                RepeaterListVoluteers.DataBind();
            }
            catch (ApplicationException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
            }
        }

        /// <summary>
        /// Removes the active on button.
        /// </summary>
        protected void RemoveActiveOnButton()
        {
            LinkGroupAll.CssClass = "button-in-active";
            LinkGroup6.CssClass = "button-in-active";
            LinkGroup5.CssClass = "button-in-active";
            LinkGroup4.CssClass = "button-in-active";
            LinkGroup3.CssClass = "button-in-active";
            LinkGroup2.CssClass = "button-in-active";
            LinkGroup1.CssClass = "button-in-active";
            LinkGroup0.CssClass = "button-in-active";
        }

        /// <summary>
        /// Sorts the service by alfabet.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="isInActived">if set to <c>true</c> [is in actived].</param>
        protected void SortServiceByAlfabet(string target, bool isInActived)
        {
            try
            {
                string condition = "";
                if (target.Length > -1)
                {
                    for (int i = 0; i < target.Length; i++)
                    {
                        if (i == 0)
                        {
                            condition += "(ContactName LIKE '" + target.Substring(i, 1) + "*' OR ";
                        }
                        else if (i == target.Length - 1)
                        {
                            if (!isInActived)
                            {
                                condition += "ContactName LIKE '" + target.Substring(i, 1) + "*') AND IsActive ='True'";
                            }
                            else
                            {
                                condition += "ContactName LIKE '" + target.Substring(i, 1) + "*')";
                            }
                        }
                        else
                        {
                            condition += "ContactName LIKE '" + target.Substring(i, 1) + "*' OR ";
                        }
                    }
                    _dataView.RowFilter = condition;
                }
                CollectionPager.PageSize = 15;
                CollectionPager.BindToControl = RepeaterListVoluteers;
                CollectionPager.DataSource = _dataView;
                RepeaterListVoluteers.DataSource = CollectionPager.DataSourcePaged;
                RepeaterListVoluteers.DataBind();
            }
            catch (ApplicationException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
            }
        }

        /// <summary>
        /// Sorts the name of the service by column.
        /// </summary>
        /// <param name="column">The column.</param>
        protected void SortServiceByColumnName(string column)
        {
            try
            {
                if (_isSort)
                {
                    _dataView.Sort = String.Format(_formatProvider, "{0} ASC", column);
                    _isSort = false;
                }
                else
                {
                    _dataView.Sort = String.Format(_formatProvider, "{0} DESC", column);
                    _isSort = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion

        #region Events
        protected void LinkGroupAllClick(object sender, EventArgs e)
        {
            ResetSortVoluteers(CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroupAll.CssClass = "button-active";
        }

        protected void LinkGroup0Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("0123456789", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup0.CssClass = "button-active";
        }

        protected void LinkGroup1Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("ABCDE", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup1.CssClass = "button-active";
        }

        protected void LinkGroup2Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("FGHIJ", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup2.CssClass = "button-active";
        }

        protected void LinkGroup3Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("KLMN", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup3.CssClass = "button-active";
        }

        protected void LinkGroup4Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("OPQR", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup4.CssClass = "button-active";
        }

        protected void LinkGroup5Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("STUV", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup5.CssClass = "button-active";
        }

        protected void LinkGroup6Click(object sender, EventArgs e)
        {
            SortServiceByAlfabet("WXYZ", CheckBoxIncludeActivate.Checked);
            RemoveActiveOnButton();
            LinkGroup6.CssClass = "button-active";
        }

        protected void SortPurposeClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("VolunteerPurpose");
        }

        protected void SortNumberTypeClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("VolunteerNo");
        }

        protected void SortByStartDateClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("StartDate");
        }

        protected void SortByEndDateClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("EndDate");
        }

        protected void SortByContactClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("ContactName");
        }

        protected void SortByActivatedClick(object sender, EventArgs e)
        {
            SortServiceByColumnName("IsActive");
        }

        protected void ButtonCreateClick(object sender, EventArgs e)
        {
            Response.Redirect("VolunteeringOpportunityDetails.aspx?action=create");
        }
        #endregion
    }
}